<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/20
 * Time: 下午1:53
 */

namespace frontend\controllers;


use common\models\User;
use common\models\WechatUser;
use Yii;
use common\models\LoginForm;

class BaseController extends \common\core\Controller{
    
    public function beforeAction($action)
    {
    
//        Yii::$app->user->login(User::findOne(['id' => 2]));
//        file_put_contents('1.txt', Yii::$app->session->get(Yii::$app->wechat->sessionParam));
//        Yii::$app->session->set(Yii::$app->wechat->sessionParam, file_get_contents('1.txt'));
        // 判断用户登陆状态
        if( Yii::$app->user->isGuest ){
            // 检测是否
            if( Yii::$app->wechat->isWechat || YII_ENV == 'dev' ){
                if( !Yii::$app->wechat->isAuthorized() ){
                    return Yii::$app->wechat->authorizeRequired()->send();
                }else{
                    $user = Yii::$app->wechat->getUser();
                    // 自动登录
                    $model = new LoginForm(['scenario' => LoginForm::SCENARIO_OAUTH]);
                    $model->login(['oauth' => WechatUser::createOauth($user->original)]);
                }
            }
        }
        
        return parent::beforeAction($action);
    }
}